using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Slobby.Common {
    public class Dispatcher<T> where T : Reciever {
        public Dictionary<Type, MethodInfo> typeFunctionMap = new Dictionary<Type, MethodInfo>();

        public Dispatcher() {
            Type recieverType = typeof(T);
            MethodInfo[] methods = recieverType.GetMethods();

            foreach (MethodInfo info in methods) {
                if (info.Name == "Recieve") {
                    ParameterInfo[] paramaters = info.GetParameters();
                    if (paramaters.Length == 1) {
                        typeFunctionMap.Add(paramaters[0].ParameterType, info);
                    }
                }
            }
        }

        public void Dispatch(T instance, object o) {
            Type inputType = o.GetType();
            MethodInfo toCall;
            if (typeFunctionMap.TryGetValue(inputType, out toCall)) {
                toCall.Invoke(instance, new object[] { o });
            }
            else {
                instance.Default(o);
            }
        }
    }
}